package net.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 	实现读写的
 * @author Administrator
 *
 */
public class TCPClientPlus {

	
	public static void main(String[] args) throws UnknownHostException, IOException {
		// 链接服务端
		Socket socket = new Socket("localhost", 8888);
		System.out.println("已连接服务器");
		
		// 获取输入流和输出流
		OutputStream out = socket.getOutputStream();
		InputStream in = socket.getInputStream();
		
		// 写
		new Thread() {
			@Override
			public void run() {
				// 循环输出数据
				Scanner scanner = new Scanner(System.in);
				while(true) {
					String content = scanner.nextLine();
					if("bye".equals(content)) {
						break;
					}
					
					try {
						out.write(content.getBytes());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				scanner.close();
			}
		}.start();
		
		// 读
		new Thread() {
			@Override
			public void run() {
				try {
					byte[] content = new byte[1024];
					int length = in.read(content);
					while(length != -1) {
						System.out.println("接收的数据是：" + new String(content, 0, length));
						length = in.read(content);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
		
	}
	
}
